/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.support;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Executable;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * 在Spring bean工厂运行时,合并了多个bean的跟节点bean定义(顶层bean元素).
 * {@link RootBeanDefinition}可能是由多个相互继承的原始bean定义创建的,正常情况下,对于普通的bean,
 * 通常会注册为{@link GenericBeanDefinition}.
 * 而{@link RootBeanDefinition}其目的的本质在于运行时统一bean定义视图.
 * <p>
 * 当然,{@link RootBeanDefinition}也可以用来在配置阶段注册单个的bean的bean定义,但是,从Spring2.5开始
 * 以编程方式注册bean定义的首选方法是{@link GenericBeanDefinition},因为{@link GenericBeanDefinition}
 * 允许动态的定义对父类的依赖,而不需要将角色硬编码为{@link RootBeanDefinition}.
 * <p>
 * <p>
 * A root bean definition represents the merged bean definition that backs
 * a specific bean in a Spring BeanFactory at runtime. It might have been created
 * from multiple original bean definitions that inherit from each other,
 * typically registered as {@link GenericBeanDefinition GenericBeanDefinitions}.
 * A root bean definition is essentially the 'unified' bean definition view at runtime.
 * <p>
 * <p>Root bean definitions may also be used for registering individual bean definitions
 * in the configuration phase. However, since Spring 2.5, the preferred way to register
 * bean definitions programmatically is the {@link GenericBeanDefinition} class.
 * GenericBeanDefinition has the advantage that it allows to dynamically define
 * parent dependencies, not 'hard-coding' the role as a root bean definition.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see GenericBeanDefinition
 * @see ChildBeanDefinition
 */
@SuppressWarnings("serial")
public class RootBeanDefinition extends AbstractBeanDefinition {
	/**
	 * 持有bean名称和别名的处理器,其本身也包含一个bean定义.
	 */
	@Nullable
	private BeanDefinitionHolder decoratedDefinition;
	/**
	 * bean定义对应的注解
	 */
	@Nullable
	private AnnotatedElement qualifiedElement;
	/**
	 * 允许缓存
	 */
	boolean allowCaching = true;
	/**
	 * 在工厂方法里是唯一的.
	 */
	boolean isFactoryMethodUnique = false;
	/**
	 * 类型解析器
	 */
	@Nullable
	volatile ResolvableType targetType;

	/**
	 * 用来缓存指定的bean定义对应的Class的字段.package-visible(包可见性)
	 * <p>
	 * Package-visible field for caching the determined Class of a given bean definition
	 */
	@Nullable
	volatile Class<?> resolvedTargetType;

	/**
	 * 用来缓存一般类型工厂方法的返回类型的字段.Package-visible(包可见性)
	 * Package-visible field for caching the return type of a generically typed factory method
	 */
	@Nullable
	volatile ResolvableType factoryMethodReturnType;

	/**
	 * 下面四个构造函数字段的通用锁
	 * Common lock for the four constructor fields below
	 */
	final Object constructorArgumentLock = new Object();

	/**
	 * 用来缓存已经解析的构造函数或者工厂方法的字段.Package-visible(包可见性)
	 * Package-visible field for caching the resolved constructor or factory method
	 */
	@Nullable
	Executable resolvedConstructorOrFactoryMethod;

	/**
	 * 将构造函数参数标记为已解决的字段. package-visible(包可见性)
	 * Package-visible field that marks the constructor arguments as resolved
	 */
	boolean constructorArgumentsResolved = false;

	/**
	 * 用于缓存完全解析的构造函数的字段.(包可见)
	 * Package-visible field for caching fully resolved constructor arguments
	 */
	@Nullable
	Object[] resolvedConstructorArguments;

	/**
	 * 缓存部分准备好的构造函数参数.(包可见)
	 * Package-visible field for caching partly prepared constructor arguments
	 */
	@Nullable
	Object[] preparedConstructorArguments;

	/**
	 * 给下面两个后处理字段的常见锁.
	 * Common lock for the two post-processing fields below
	 */
	final Object postProcessingLock = new Object();

	/**
	 * 只是已应用MergedBeanDefinitionPostProcessor的字段.(包可见)
	 * Package-visible field that indicates MergedBeanDefinitionPostProcessor having been applied
	 */
	boolean postProcessed = false;

	/**
	 * 表明在实例化之前的后处理器已经被写入.(包可见)
	 * Package-visible field that indicates a before-instantiation post-processor having kicked in
	 */
	@Nullable
	volatile Boolean beforeInstantiationResolved;
	/**
	 * 外部管理的配置成员
	 */
	@Nullable
	private Set<Member> externallyManagedConfigMembers;

	@Nullable
	private Set<String> externallyManagedInitMethods;

	@Nullable
	private Set<String> externallyManagedDestroyMethods;


	/**
	 * 创建一个RootBeanDefinition实例.
	 * Create a new RootBeanDefinition, to be configured through its bean
	 * properties and configuration methods.
	 *
	 * @see #setBeanClass
	 * @see #setScope
	 * @see #setConstructorArgumentValues
	 * @see #setPropertyValues
	 */
	public RootBeanDefinition() {
		super();
	}

	/**
	 * 为单例bean创建一个RootBeanDefinition.
	 * Create a new RootBeanDefinition for a singleton.
	 *
	 * @param beanClass the class of the bean to instantiate
	 * @see #setBeanClass
	 */
	public RootBeanDefinition(@Nullable Class<?> beanClass) {
		super();
		setBeanClass(beanClass);
	}

	/**
	 * 为单例bean创建一个新的RootBeanDefinition,通过调用指定的提供者来构造每一个实例.
	 * <p>
	 * Create a new RootBeanDefinition for a singleton bean, constructing each instance
	 * through calling the given supplier (possibly a lambda or method reference).
	 *
	 * @param beanClass        the class of the bean to instantiate
	 * @param instanceSupplier the supplier to construct a bean instance,
	 *                         as an alternative to a declaratively specified factory method
	 * @see #setInstanceSupplier
	 * @since 5.0
	 */
	public <T> RootBeanDefinition(@Nullable Class<T> beanClass, @Nullable Supplier<T> instanceSupplier) {
		super();
		setBeanClass(beanClass);
		setInstanceSupplier(instanceSupplier);
	}

	/**
	 * 为单例bean创建一个新的RootBeanDefinition,通过调用指定的提供者来构造每一个实例.
	 * <p>
	 * Create a new RootBeanDefinition for a scoped bean, constructing each instance
	 * through calling the given supplier (possibly a lambda or method reference).
	 *
	 * @param beanClass        the class of the bean to instantiate
	 * @param scope            the name of the corresponding scope
	 * @param instanceSupplier the supplier to construct a bean instance,
	 *                         as an alternative to a declaratively specified factory method
	 * @see #setInstanceSupplier
	 * @since 5.0
	 */
	public <T> RootBeanDefinition(@Nullable Class<T> beanClass, String scope, @Nullable Supplier<T> instanceSupplier) {
		super();
		setBeanClass(beanClass);
		setScope(scope);
		setInstanceSupplier(instanceSupplier);
	}

	/**
	 * 通过指定的自动注入模式,为单例创建一个RootBeanDefinition.
	 * Create a new RootBeanDefinition for a singleton,
	 * using the given autowire mode.
	 *
	 * @param beanClass       the class of the bean to instantiate
	 * @param autowireMode    by name or type, using the constants in this interface
	 * @param dependencyCheck whether to perform a dependency check for objects
	 *                        (not applicable to autowiring a constructor, thus ignored there)
	 */
	public RootBeanDefinition(@Nullable Class<?> beanClass, int autowireMode, boolean dependencyCheck) {
		super();
		setBeanClass(beanClass);
		setAutowireMode(autowireMode);
		if (dependencyCheck && getResolvedAutowireMode() != AUTOWIRE_CONSTRUCTOR) {
			setDependencyCheck(DEPENDENCY_CHECK_OBJECTS);
		}
	}

	/**
	 * 通过提供的构造函数参数和属性来为单例创建一个新的RootBeanDefinition.
	 * Create a new RootBeanDefinition for a singleton,
	 * providing constructor arguments and property values.
	 *
	 * @param beanClass the class of the bean to instantiate
	 * @param cargs     the constructor argument values to apply
	 * @param pvs       the property values to apply
	 */
	public RootBeanDefinition(@Nullable Class<?> beanClass, @Nullable ConstructorArgumentValues cargs,
							  @Nullable MutablePropertyValues pvs) {

		super(cargs, pvs);
		setBeanClass(beanClass);
	}

	/**
	 * 通过Bean类名为单例创建一个RootBeanDefinition.
	 * Create a new RootBeanDefinition for a singleton,
	 * providing constructor arguments and property values.
	 * <p>Takes a bean class name to avoid eager loading of the bean class.
	 *
	 * @param beanClassName the name of the class to instantiate
	 */
	public RootBeanDefinition(String beanClassName) {
		setBeanClassName(beanClassName);
	}

	/**
	 * 通过Bean类名,构造参数和属性构造一个单例的RootBeanDefinition.
	 * <p>
	 * Create a new RootBeanDefinition for a singleton,
	 * providing constructor arguments and property values.
	 * <p>Takes a bean class name to avoid eager loading of the bean class.
	 *
	 * @param beanClassName the name of the class to instantiate
	 * @param cargs         the constructor argument values to apply
	 * @param pvs           the property values to apply
	 */
	public RootBeanDefinition(String beanClassName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
		super(cargs, pvs);
		setBeanClassName(beanClassName);
	}

	/**
	 * 深copy一个指定RootBeanDefinition的副本.
	 * <p>
	 * Create a new RootBeanDefinition as deep copy of the given
	 * bean definition.
	 *
	 * @param original the original bean definition to copy from
	 */
	public RootBeanDefinition(RootBeanDefinition original) {
		super(original);
		this.decoratedDefinition = original.decoratedDefinition;
		this.qualifiedElement = original.qualifiedElement;
		this.allowCaching = original.allowCaching;
		this.isFactoryMethodUnique = original.isFactoryMethodUnique;
		this.targetType = original.targetType;
	}

	/**
	 * 深copy一个指定BeanDefinition的副本作为RootBeanDefinition.
	 * Create a new RootBeanDefinition as deep copy of the given
	 * bean definition.
	 *
	 * @param original the original bean definition to copy from
	 */
	RootBeanDefinition(BeanDefinition original) {
		super(original);
	}

	/**
	 * 顶层bean无父引用.
	 *
	 * @return
	 */
	@Override
	public String getParentName() {
		return null;
	}

	/**
	 * 顶层bean无父引用.
	 *
	 * @param parentName
	 */
	@Override
	public void setParentName(@Nullable String parentName) {
		if (parentName != null) {
			throw new IllegalArgumentException("Root bean cannot be changed into a child bean with parent reference");
		}
	}

	/**
	 * 通过当前bean装饰注册的目标bean定义.
	 * Register a target definition that is being decorated by this bean definition.
	 */
	public void setDecoratedDefinition(@Nullable BeanDefinitionHolder decoratedDefinition) {
		this.decoratedDefinition = decoratedDefinition;
	}

	/**
	 * 返回正在被当前bean装饰的bean定义.
	 * <p>
	 * Return the target definition that is being decorated by this bean definition, if any.
	 */
	@Nullable
	public BeanDefinitionHolder getDecoratedDefinition() {
		return this.decoratedDefinition;
	}

	/**
	 * 指定一个AnnotatedElement定义限定符来代替目标类或者工厂方法.
	 * <p>
	 * Specify the {@link AnnotatedElement} defining qualifiers,
	 * to be used instead of the target class or factory method.
	 *
	 * @see #setTargetType(ResolvableType)
	 * @see #getResolvedFactoryMethod()
	 * @since 4.3.3
	 */
	public void setQualifiedElement(@Nullable AnnotatedElement qualifiedElement) {
		this.qualifiedElement = qualifiedElement;
	}

	/**
	 * 返回定义的限定符的AnnotatedElement,否则就会查找工厂方法和目标类.
	 * Return the {@link AnnotatedElement} defining qualifiers, if any.
	 * Otherwise, the factory method and target class will be checked.
	 *
	 * @since 4.3.3
	 */
	@Nullable
	public AnnotatedElement getQualifiedElement() {
		return this.qualifiedElement;
	}

	/**
	 * 如果事先已知,则指定此Bean定义的一个含泛型的bean定义.
	 * Specify a generics-containing target type of this bean definition, if known in advance.
	 *
	 * @since 4.3.3
	 */
	public void setTargetType(ResolvableType targetType) {
		this.targetType = targetType;
	}

	/**
	 * 如果已知,指定此Bean定义的目标类型.
	 * Specify the target type of this bean definition, if known in advance.
	 *
	 * @since 3.2.2
	 */
	public void setTargetType(@Nullable Class<?> targetType) {
		this.targetType = (targetType != null ? ResolvableType.forClass(targetType) : null);
	}

	/**
	 * 如果已知,返回此Bean定义的目标类型,可以预先指定或在第一个实例化是解析.
	 * <p>
	 * Return the target type of this bean definition, if known
	 * (either specified in advance or resolved on first instantiation).
	 *
	 * @since 3.2.2
	 */
	@Nullable
	public Class<?> getTargetType() {
		if (this.resolvedTargetType != null) {
			return this.resolvedTargetType;
		}
		ResolvableType targetType = this.targetType;
		return (targetType != null ? targetType.resolve() : null);
	}

	/**
	 * 制定一个引用非重载方法的工厂方法名称.
	 * <p>
	 * Specify a factory method name that refers to a non-overloaded method.
	 */
	public void setUniqueFactoryMethodName(String name) {
		Assert.hasText(name, "Factory method name must not be empty");
		setFactoryMethodName(name);
		this.isFactoryMethodUnique = true;
	}

	/**
	 * 检查给定的候选值是否符合工厂方法.
	 * Check whether the given candidate qualifies as a factory method.
	 */
	public boolean isFactoryMethod(Method candidate) {
		return candidate.getName().equals(getFactoryMethodName());
	}

	/**
	 * 如果可用的话,就将已经解析的工厂方法作为java方法对象返回.
	 * Return the resolved factory method as a Java Method object, if available.
	 *
	 * @return the factory method, or {@code null} if not found or not resolved yet
	 */
	@Nullable
	public Method getResolvedFactoryMethod() {
		synchronized (this.constructorArgumentLock) {
			Executable candidate = this.resolvedConstructorOrFactoryMethod;
			return (candidate instanceof Method ? (Method) candidate : null);
		}
	}

	/**
	 * 注册外部管理的配置成员.
	 * @param configMember	配置成员.
	 */
	public void registerExternallyManagedConfigMember(Member configMember) {
		synchronized (this.postProcessingLock) {
			if (this.externallyManagedConfigMembers == null) {
				this.externallyManagedConfigMembers = new HashSet<>(1);
			}
			this.externallyManagedConfigMembers.add(configMember);
		}
	}

	/**
	 * 判断是否为外部管理的配置成员.
	 * @param configMember 配置成员.
	 * @return true or false.
	 */
	public boolean isExternallyManagedConfigMember(Member configMember) {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedConfigMembers != null &&
					this.externallyManagedConfigMembers.contains(configMember));
		}
	}

	/**
	 * 注册外部管理的初始化方法.
	 * @param initMethod 初始化方法
	 */
	public void registerExternallyManagedInitMethod(String initMethod) {
		synchronized (this.postProcessingLock) {
			if (this.externallyManagedInitMethods == null) {
				this.externallyManagedInitMethods = new HashSet<>(1);
			}
			this.externallyManagedInitMethods.add(initMethod);
		}
	}

	/**
	 * 是否为注册外部管理的初始化方法.
	 * @param initMethod	初始化方法.
	 * @return true or false.
	 */
	public boolean isExternallyManagedInitMethod(String initMethod) {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedInitMethods != null &&
					this.externallyManagedInitMethods.contains(initMethod));
		}
	}
	/**
	 * 注册外部管理的销毁方法.
	 * @param destroyMethod 销毁方法
	 */
	public void registerExternallyManagedDestroyMethod(String destroyMethod) {
		synchronized (this.postProcessingLock) {
			if (this.externallyManagedDestroyMethods == null) {
				this.externallyManagedDestroyMethods = new HashSet<>(1);
			}
			this.externallyManagedDestroyMethods.add(destroyMethod);
		}
	}
	/**
	 * 是否为注册外部管理的销毁方法.
	 * @param destroyMethod	销毁方法.
	 * @return true or false.
	 */
	public boolean isExternallyManagedDestroyMethod(String destroyMethod) {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedDestroyMethods != null &&
					this.externallyManagedDestroyMethods.contains(destroyMethod));
		}
	}

	/**
	 * 返回当前RootBeanDefinition的一个深Copy.
	 * @return
	 */
	@Override
	public RootBeanDefinition cloneBeanDefinition() {
		return new RootBeanDefinition(this);
	}

	@Override
	public boolean equals(Object other) {
		return (this == other || (other instanceof RootBeanDefinition && super.equals(other)));
	}

	@Override
	public String toString() {
		return "Root bean: " + super.toString();
	}

}
